package m.jclecai.com.activity.follow;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.Response.ResHotOrederDetail;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.fragment.follow.HotOrderDetailFragment;
import m.jclecai.com.fragment.follow.HotOrderPeopleFragment;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.common.AddDelEditTextView;

/**
 * Created by Dinosa on 2017/11/17.
 * 跟单详情
 */

public class HotOrderDetailActivity extends BaseActivity {


    @BindView(R.id.iv_user_icon)
    ImageView mIvUserIcon;

    @BindView(R.id.tv_username)
    TextView mTvUsername;

    @BindView(R.id.tv_follow)
    TextView mTvFollow;

    @BindView(R.id.tv_win_total_money)
    TextView mTvWinTotalMoney;

    @BindView(R.id.tv_unit_award)
    TextView mTvUnitAward;

    @BindView(R.id.tv_lottery_name)
    TextView mTvLotteryName;

    @BindView(R.id.tv_expected_report)
    TextView mTvExpectedReport;

    @BindView(R.id.tv_desc)
    TextView mTvDesc;

    @BindView(R.id.tv_one_money)
    TextView mTvOneMoney;

    @BindView(R.id.tv_follow_money)
    TextView mTvFollowMoney;

    @BindView(R.id.tv_min_money)
    TextView mTvMinMoney;

    @BindView(R.id.tv_order_number)
    TextView mTvOrderNumber;

    @BindView(R.id.tv_create_time)
    TextView mTvCreateTime;

    @BindView(R.id.tl_tablayout)
    TabLayout mTlTablayout;

    @BindView(R.id.vp_view_pager)
    ViewPager mVpViewPager;

    @BindView(R.id.rb_10)
    RadioButton mRb10;

    @BindView(R.id.rb_20)
    RadioButton mRb20;

    @BindView(R.id.rb_50)
    RadioButton mRb50;

    @BindView(R.id.rb_100)
    RadioButton mRb100;

    @BindView(R.id.rg_group)
    RadioGroup mRgGroup;

    @BindView(R.id.tv_bet_total_money)
    TextView mTvBetTotalMoney;

    @BindView(R.id.tv_bet)
    TextView mTvBet;

    @BindView(R.id.tv_play_mode)
    TextView mTvPlayMode;

    @BindView(R.id.activity_follow_order_detail)
    LinearLayout mActivityFollowOrderDetail;

    @BindView(R.id.ll_follow_container)
    LinearLayout mLlFollowContainer;

    @BindView(R.id.addAndDelView)
    AddDelEditTextView mAddDelEditTextView;

    @BindView(R.id.tv_award_number)
    TextView mTvAwardNumber;

    @BindView(R.id.rl_award_bg)
    RelativeLayout mRlAwardBg;


    public static final String ORDER_ID = "orderId";

    public String[] pagerTitles = {"方案详情", "跟单用户(0)"};

    private HotOrderViewPagerAdapter mHotOrderViewPagerAdapter;
    private ArrayList<BaseFragment> mBaseFragments;
    private HotOrderDetailFragment mHotOrderDetailFragment;
    private HotOrderPeopleFragment mHotOrderPeopleFragment;

    private String mPlanId;
    private int mCurBetNumber;
    private ResHotOrederDetail mOrederDetail;


    @Override
    protected int getContentView() {
        return R.layout.activity_follow_order_detail;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("跟单详情");
        leftOptionText("");
    }

    @OnClick(R.id.tv_follow)
    public void onClickFollow(View view) {
        //这里我们要切换关注与取消关注；
        String s = mTvFollow.getText().toString();
        if ("已关注".equals(s)) {
            doFollowRequest("del");
        } else {
            //取消关注
            doFollowRequest("add");
        }

    }

    private void doFollowRequest(String operation) {
        final HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user", PreferenceUtil.getUserName(this));
        paramsMap.put("password", PreferenceUtil.getPassword(this));
        paramsMap.put("type", operation);
        paramsMap.put("id", mResHotOrderDetail.getUser_id());

        HttpManager.postAsyn(Constant_Url.FOLLOW_HOT_PEOPLE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络异常");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {

                    ProofBean proofBean = FastOk.get(response, ProofBean.class);
                    if ("0".equals(proofBean.getStatus())) {
                        DisPlay(proofBean.getMessage());
                        String followStatue = mTvFollow.getText().toString().equals("已关注") ? "+ 关注" : "已关注";
                        mTvFollow.setText(followStatue);
                    } else {
                        DisPlay(proofBean.getMessage());
                    }
                } else {
                    DisPlay("网络异常!!!");
                }
            }
        }, paramsMap);
    }

    @Override
    protected void initData() {
        super.initData();
        //这里我们要做的一个操作就是显示初始化数据；

        mBaseFragments = new ArrayList<>();
        mHotOrderDetailFragment = new HotOrderDetailFragment();
        mHotOrderPeopleFragment = new HotOrderPeopleFragment();

        mBaseFragments.add(mHotOrderDetailFragment);
        mBaseFragments.add(mHotOrderPeopleFragment);

        mHotOrderViewPagerAdapter = new HotOrderViewPagerAdapter(getSupportFragmentManager());
        mVpViewPager.setAdapter(mHotOrderViewPagerAdapter);
        mTlTablayout.setupWithViewPager(mVpViewPager);

        mPlanId = getIntent().getStringExtra(ORDER_ID);
        requestOrderDetail(mPlanId);
    }

    private ResHotOrederDetail mResHotOrderDetail;

    private void requestOrderDetail(String planId) {

        showDialog();
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("id", planId);
        paramsMap.put("user", PreferenceUtil.getUserName(this));

        HttpManager.postAsyn(Constant_Url.HOT_ORDER_DETAIL, new HttpManager.StringCallback() {

            @Override
            public void onFailure(Request request, IOException e) {

                dissDialog();
                DisPlay("网络异常!!!");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                try {
                    if (!TextUtils.isEmpty(response)) {
                        mResHotOrderDetail = FastOk.get(response, ResHotOrederDetail.class);
                        if (mResHotOrderDetail != null) {
                            if ("0".equals(mResHotOrderDetail.getStatus())) {
                                updateUI(mResHotOrderDetail);
                            } else {
                                DisPlay(mResHotOrderDetail.getMessage());
                            }
                        } else {
                            DisPlay("网络异常!!");
                        }
                    } else {
                        DisPlay("网络异常!!");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DisPlay("网络异常!!");
                }

            }
        }, paramsMap);

    }

    /**
     * 刷新界面；
     *
     * @param orederDetail
     */
    private void updateUI(ResHotOrederDetail orederDetail) {


        mOrederDetail = orederDetail;

        if (orederDetail.getState().equals("1")) {

            mTvAwardNumber.setVisibility(View.INVISIBLE);
            mRlAwardBg.setBackgroundResource(R.drawable.follow_no_win_img);
            mRlAwardBg.setVisibility(View.VISIBLE);

        } else if (orederDetail.getState().equals("2")) {


            mTvAwardNumber.setVisibility(View.INVISIBLE);
            mRlAwardBg.setVisibility(View.VISIBLE);
            mRlAwardBg.setBackgroundResource(R.drawable.follow_no_win_img);

        } else if (orederDetail.getState().equals("3")) {


            mTvAwardNumber.setVisibility(View.VISIBLE);
            mTvAwardNumber.setText("￥"+orederDetail.getWin_money());
            mRlAwardBg.setVisibility(View.VISIBLE);
            mRlAwardBg.setBackgroundResource(R.drawable.follow_win);

        } else {
            mRlAwardBg.setVisibility(View.INVISIBLE);
        }

        mTvUnitAward.setText("7日盈利率: "+orederDetail.getPayback());
        mTvExpectedReport.setText("预计回报："+orederDetail.getReturnrate()+"倍");


        //用户信息
        mTvUsername.setText(orederDetail.getUsername());
        Glide.with(this)
                .load(orederDetail.getUser_face())
                .into(mIvUserIcon);
        mTvWinTotalMoney.setText("创造价值:" + orederDetail.getAll_winmoneys_total());
        mTvPlayMode.setText(orederDetail.getMilitary_total().replace("/","中"));

        if ("1".equals(orederDetail.getAttention())) {
            //这里表示已经关注了
            mTvFollow.setText("已关注");
        } else {
            mTvFollow.setText("+ 关注");
        }
        mAddDelEditTextView.setBetNumber(1);
        mTvBetTotalMoney.setText("共" + orederDetail.getFollow_minmoney() + "元");

        if (orederDetail.getCan_follow() > 0) {
            //这里表示可以跟单；
            mLlFollowContainer.setVisibility(View.VISIBLE);
        } else {
            mLlFollowContainer.setVisibility(View.GONE);
        }


        String method = orederDetail.getMethodname().replace("*", "串");
        //跟单描述
        mTvLotteryName.setText(orederDetail.getLotteryname() + "  " + method);
        mTvDesc.setText(orederDetail.getTitle());

        mTvOneMoney.setText("自购:    " + orederDetail.getOne_money());
        mTvFollowMoney.setText("跟单:    " + orederDetail.getFollow_money());
        mTvMinMoney.setText(orederDetail.getFollow_minmoney() + "元起投");

        mTvOrderNumber.setText(orederDetail.getProjectno());
        mTvCreateTime.setText(orederDetail.getAddtime());

        //这里我们要对Fragment进行一个赋值操作；

        pagerTitles[1] = "跟单用户" + "(" + orederDetail.getFollow_count() + ")";
        mHotOrderDetailFragment.updateUI(orederDetail);
        mHotOrderPeopleFragment.updateUI(orederDetail, mPlanId);

        mHotOrderViewPagerAdapter.notifyDataSetChanged();

    }

    @Override
    protected void initListener() {
        super.initListener();

        mRgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_10:
                        mAddDelEditTextView.setBetNumber(10);
                        break;
                    case R.id.rb_20:
                        mAddDelEditTextView.setBetNumber(20);
                        break;
                    case R.id.rb_50:
                        mAddDelEditTextView.setBetNumber(50);
                        break;
                    case R.id.rb_100:
                        mAddDelEditTextView.setBetNumber(100);
                        break;
                }
            }
        });


        mAddDelEditTextView.setOnBetNumberChangeListener(new AddDelEditTextView.OnBetNumberChangeListener() {

            @Override
            public void onBetNumberChange(int betNumber) {

                mCurBetNumber = betNumber;
                //这里我们做的操作
                if (betNumber == 10) {
                    mRb10.setChecked(true);
                } else if (betNumber == 20) {
                    mRb20.setChecked(true);
                } else if (betNumber == 50) {
                    mRb50.setChecked(true);
                } else if (betNumber == 100) {
                    mRb100.setChecked(true);
                }
                //这里我们同时是需要刷新金额的；
                int needMoney = 0;
                try {
                    needMoney=betNumber * Integer.parseInt(mOrederDetail.getFollow_minmoney());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                mTvBetTotalMoney.setText("共" + needMoney + "元");
            }
        });

        mTvBet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里我们要做的一个操作就是跳转到投注的页面

                if (mResHotOrderDetail == null) {
                    return;
                }

                String lotteryName = mResHotOrderDetail.getLotteryname();
                int totalMoney = Integer.parseInt(mResHotOrderDetail.getFollow_minmoney()) * mCurBetNumber;

                Intent intent = FollowOrderConfirmActivity.getIntent(HotOrderDetailActivity.this, mPlanId, mCurBetNumber + "", lotteryName, totalMoney + "");
                startActivity(intent);
            }
        });
    }


    public static Intent getIntent(Context context, String orderId) {
        Intent intent = new Intent(context, HotOrderDetailActivity.class);
        intent.putExtra(ORDER_ID, orderId);
        return intent;
    }


    public class HotOrderViewPagerAdapter extends FragmentPagerAdapter {

        @Override
        public CharSequence getPageTitle(int position) {
            return pagerTitles[position];
        }

        public HotOrderViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            return mBaseFragments.get(position);
        }

        @Override
        public int getCount() {
            return pagerTitles.length;
        }
    }
}
